from django.core.cache import cache
import uuid
# import time

class RedisLock:
    def __init__(self, key, timeout=60):
        self.key = key
        self.timeout = timeout
        self.cache = cache
        self.identifier = str(uuid.uuid4())

    def acquire(self):
        r = self.cache.get(self.key)
        if r is None:
            return self.cache.set(self.key, self.identifier, timeout=self.timeout)
        s = self.timeout
        while True:
            if s == 0:
                return None
            if self.cache.get(self.key):
                return self.cache.set(self.key, self.identifier, timeout=self.timeout)
            s = s - 1
            

    def release(self):
        self.cache.delete(self.key)
        return True